package com.example.androidone.utils;

import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NALParser {
    private static final String TAG = "NALParser";
    private static final byte[] START_CODE = {0x00, 0x00, 0x00, 0x01};

    public List<byte[]> parseNALUnits(byte[] data) {
        List<byte[]> nalUnits = new ArrayList<>();
        int startIndex = 0;

        // 打印前几个字节用于调试
        if (data.length > 16) {
            StringBuilder sb = new StringBuilder("First 16 bytes: ");
            for (int i = 0; i < 16; i++) {
                sb.append(String.format("%02X ", data[i]));
            }
            Log.d(TAG, sb.toString());
        }

        // 首个NAL单元的类型
        if (data.length > 5) {
            int nalType = (data[4] >> 1) & 0x3F;
            Log.d(TAG, "First NAL unit type: " + nalType);
        }

        for (int i = 0; i < data.length - 3; i++) {
            if (isStartCode(data, i)) {
                if (startIndex > 0) {
                    byte[] nalUnit = Arrays.copyOfRange(data, startIndex, i);
                    int type = (nalUnit[0] >> 1) & 0x3F;
                    Log.d(TAG, String.format("Found NAL unit type %d, size: %d", type, nalUnit.length));
                    nalUnits.add(nalUnit);
                }
                startIndex = i + 4;
                i += 3;
            }
        }

        if (startIndex < data.length) {
            byte[] nalUnit = Arrays.copyOfRange(data, startIndex, data.length);
            int type = (nalUnit[0] >> 1) & 0x3F;
            Log.d(TAG, String.format("Found final NAL unit type %d, size: %d", type, nalUnit.length));
            nalUnits.add(nalUnit);
        }

        Log.d(TAG, "Parsed " + nalUnits.size() + " NAL units");
        return nalUnits;
    }

    private boolean isStartCode(byte[] data, int offset) {
        if (offset + 4 > data.length) return false;
        for (int i = 0; i < 4; i++) {
            if (data[offset + i] != START_CODE[i]) return false;
        }
        return true;
    }
}